#pragma once
#include <iostream>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

// 上层业务：将客户端发来的数据 解码+反序列化 计算 序列化+编码
class Calculator
{
public:
    Calculator()
    {
    }

    // 接收一个请求 处理请求 返回响应
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp._result = req.x + req.y;
            break;
        case '-':
            resp._result = req.x - req.y;
            break;
        case '*':
            resp._result = req.x * req.y;
            break;
        case '/':
        {
            if (req.y == 0)
                resp._code = Div_Zero;
            else
                resp._result = req.x / req.y;
        }
        break;
        case '%':
        {
            if (req.y == 0)
                resp._code = Mod_Zero;
            else
                resp._result = req.x % req.y;
        }
        break;
        default:
            resp._code = Other_Oper;
            break;
        }

        return resp;
    }

    // "len"\n"10 + 20"\n
    // 接收客户端从网络中发来的数据 解码+反序列化 构建请求对象 --> 调用业务层计算 --> 序列化+编码
    std::string Handler(std::string &stringMsg)
    {
        std::string tmpBuffer;
        bool ret = Decode(stringMsg, &tmpBuffer); // "len"\n"10 + 20"\n --> "10 + 20"
        if (!ret)
            return "";

        Request req;
        ret = req.Deserialize(tmpBuffer); // "10 + 20" ->x=10 op=+ y=20
        if (!ret)
            return "";

        tmpBuffer = "";
        Response resp = CalculatorHelper(req); // result=30 code=0;

        resp.Serialize(&tmpBuffer);    // "30 0"
        tmpBuffer = Encode(tmpBuffer); // "len"\n"30 0"

        return tmpBuffer;
    }

    ~Calculator()
    {
    }
};